<template>
  <div>
    <a-modal
        :title="currTitle()"
        :visible="visible"
        @cancel="showModel(false)"
    >
      <template>
        <a-table
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :columns="columns"
            :data-source="dataSource"
            :pagination="{defaultPageSize:100, hideOnSinglePage:true}"
        >
          <span slot="action" slot-scope="text, record">
            <a v-if="showOfflineLink(record)"  @click="ctrlUserOffline(record)">强制下线</a>
            <span v-else>当前</span>
          </span>
        </a-table>
      </template>
      <template slot="footer">
        <a-button type="primary"  @click="multiDel">批量删除</a-button>
        <a-button @click="showModel(false)">关闭</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import {
  getAction,
  postAction
} from '@/api/manage'

import {
  ACCESS_TOKEN
} from "@/store/mutation-types"
import Vue from "vue";
export default {
  name: "UserOnlineModel",
  data() {
    return {
      visible: false,
      selectedRowKeys:[
      ],
      userName:"",
      userID:"",
      currentClientIndex:0, // 记录当前客户端在table中的索引, 用于禁止选中当前客户端
      dataSource: [],
      columns: [
        {
          title: '登录时间',
          align: "center",
          dataIndex: 'loginTimeForShow',
          key: 'loginTimeForShow',
        },
        {
          title: 'IP地址',
          align: "center",
          dataIndex: 'ip',
          key: 'ip',
        },
        {
          title: '操作',
          align: "center",
          dataIndex: 'action',
          key: 'action',
          scopedSlots: { customRender: 'action' },
          width: 100,
        },
      ],
      url: {
        list: "/sys/user/user-clients-list",
        kickClient: "/sys/user/kick-client",
        kickClientBatch: "/sys/user/kick-client-batch"
      }
    }
  },
  methods: {
    currTitle() {
      let str = '[ ' + this.userName + ' ]的登录客户端详细'
      return str;
    },
    handleOk(e) {
      console.log(e)
      this.visible = false;
    },
    getData() {
      let that = this;
      getAction(that.url.list + "/" + that.userID).then((res) => {
        if (res.code === "00000") {
          that.dataSource = res.data;
          for(let i=0; i<that.dataSource.length; i++) {
            that.dataSource[i].key = i;
          }
          console.log(that.dataSource)
        }
        else {
          that.dataSource = [];
        }
      });
    },
    setUserID(userid, username){
      this.userID = userid;
      this.userName = username;
      if (this.userID.length !== 0) {
        this.getData();
      }
    },
    showModel(visible) {
      this.visible = visible;
    },
    multiDel() {
      let params = {
        idList:[]
      };
      for (let i=0; i<this.selectedRowKeys.length; i++) {
        if (this.selectedRowKeys[i] === this.currentClientIndex) {
          continue;
        }
        if (this.dataSource[i]) {
          params.idList.push(this.dataSource[i].token)
        }
      }

      if (params.idList.length === 0) {
        this.$message.warning("无法强制下线当前客户端登录，请点击系统右上角退出按钮")
        return;
      }

      console.log(params)
      let that = this;
      postAction(this.url.kickClientBatch, params).then((res) => {
        if (res.code == "00000") {
          that.$message.success("强制下线客户端成功")
        } else {
          that.$message.warning("强制下线客户端失败:" + res.msg)
        }
        that.getData();
      })
    },
    tokenFilter(token) {
      let strStart = token.indexOf(this.userID)
      if (strStart === -1)
        return "";
      strStart += this.userID.length + 1; // userid + ':'
      return token.substring(strStart)
    },
    ctrlUserOffline(record) {
      console.log(record)
      let that = this;
      let token = record.token;
      // console.log(token, record.token)
      this.$confirm({
        title: '确认',
        content: '是否强制下线此客户端登录?',
        onOk() {
          getAction(that.url.kickClient + "/" + token).then((res) => {
            if (res.code === "00000") {
              that.$message.success("强制下线客户端成功")
            }
            else {
              that.$message.warning("强制下线客户端失败:" + res.msg)
            }
            that.getData();
            that.$emit('dataUpdate');
          });
        },
        onCancel() {},
      });
    },
    showOfflineLink(record) {
      // console.log(record)
      if (record.token.indexOf(Vue.ls.get(ACCESS_TOKEN)) !== -1) {
        this.currentClientIndex = record.key;
        return false;
      }
      return true;
    },
    onSelectChange(selectedRowKeys) {
      // let index = -1;
      // for (let i=0; i<selectedRowKeys.length; i++) {
      //   if (selectedRowKeys[i] === this.currentClientIndex) {
      //     index = i;
      //   }
      // }
      // if (index !== -1) {
      //   selectedRowKeys.splice(index, 1);
      // }
      this.selectedRowKeys = selectedRowKeys;
      // console.log(this.currentClientIndex, this.selectedRowKeys)
    },
  }
}
</script>

<style scoped>

</style>